package utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Vector;
import java.util.regex.Pattern;

public class MultipleFileSelector {
	private ArrayList<String> selectedFiles = new ArrayList<String>();

	public MultipleFileSelector(String path) {
		addDirectory(path);
	}

	public void addDirectory(String path) {

		// Process the path string
		if (System.getProperty("os.name").contains("Windows")) {
			if (path.charAt(path.length() - 1) != '\\') {
				path = path.concat("\\");
			}
		} else {
			if (path.charAt(path.length() - 1) != '/') {
				path = path.concat("/");
			}
		}

		// Process the file created from the path
		File root = new File(path);
		if (root.isDirectory()) {
			for (String entry : root.list()) {
				File newItem = new File(path + entry);
				if (newItem.isFile()) {
					selectedFiles.add(path + entry);
				} else if (newItem.isDirectory()) {
					addDirectory(path + entry);
				}
			}
		} else {
			System.out.println(root + " is not a directory!");
			selectedFiles.add(path);
		}
	}

	public String toString() {
		if (selectedFiles.isEmpty()) {
			return null;
		} else {
			String selected = "";
			for (String file : selectedFiles) {
				selected = selected.concat(file);
			}
			return selected;
		}
	}

	public Vector<String> getAllFileStrings() {
		return new Vector<String>(selectedFiles);
	}

	/**
	 * Filter is given in regex form
	 * 
	 * @param regex
	 *            that represents the form of the file name
	 * @return All files that match the regex, which are to be selected
	 */
	public Vector<String> getAllFileStrings(String regex) {
		Vector<String> selected = new Vector<String>();
		Pattern p = Pattern.compile(regex);
		for (String entry : selectedFiles) {
			if (p.matcher(entry).matches()) {
				selected.add(entry);
			}
		}
		return selected;
	}

	public String getSelectedToString() {
		String display = "";
		for (String entry : selectedFiles) {
			display = display.concat(entry + "\n");
		}
		return display;
	}
}
